<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class Importer extends BaseModel
{
    protected $table = "sys_importers";

    protected $appends = ['dealers_name'];

    protected $fillable = [
        'name',
        'linkman',
        'tel',
        'email',
        'area_code',
        'area_name',
        'user_id',
        'updater',
        'creator',
        'remark',
        'detail',
    ];

    public function dealers()
    {
        return $this->belongsToMany('App\Model\Dealer','sys_importer_dealer_relation','importer_id','dealer_id');
    }

    public function getDealersNameAttribute()
    {
        if ($this->id){
            $rows = DB::table('sys_dealers')->whereRaw('id in (select dealer_id from sys_importer_dealer_relation where importer_id='.$this->id.')')
                ->select('name')->pluck('name')->toArray();
            return $rows?implode(',',$rows):'';
        }
        return null;
    }
}
